#ifndef _SKBitmap_gdi_H_
#define _SKBitmap_gdi_H_

#include "SkBitmapWin.h"

bool InitBitmapWin(SkBitmapWin& bitmap_win)
{
	// 初始化
	HDC hdc = GetDC(NULL);
	m_screenW = GetDeviceCaps(hdc, HORZRES);
	m_screenH = GetDeviceCaps(hdc, VERTRES);
	m_screenBpp = GetDeviceCaps(hdc, BITSPIXEL);
	ReleaseDC(NULL, hdc);

	// 设置skia屏幕位图信息
	if (m_screenBpp == 16)
		m_bmpConfig = SkBitmap::kRGB_565_Config; // RGB565
	else if (m_screenBpp == 24 || m_screenBpp == 32)
		m_bmpConfig = SkBitmap::kARGB_8888_Config;

	// 创建后台显示位图
	BITMAPINFO *bitmapInfo = NULL;
    struct {
		BITMAPINFOHEADER bmiHeader;
		RGBQUAD bmiColors[3];
    } bmi_stack;
	BITMAPINFO* bitmap_info = (BITMAPINFO *)&bmi_stack;

	bitmap_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bitmap_info->bmiHeader.biWidth = m_screenW;
    bitmap_info->bmiHeader.biHeight = -m_screenH; /* top-down */
    bitmap_info->bmiHeader.biSizeImage = 0;
    bitmap_info->bmiHeader.biXPelsPerMeter = 0; /* unused here */
    bitmap_info->bmiHeader.biYPelsPerMeter = 0; /* unused here */
    bitmap_info->bmiHeader.biPlanes = 1;

	if (m_screenBpp == 16)
	{
		bitmap_info->bmiHeader.biBitCount = 16;
		bitmap_info->bmiHeader.biCompression = BI_BITFIELDS;
		bitmap_info->bmiHeader.biSizeImage = m_screenH * ((m_screenW * 2 + 3) & ~3);
		bitmap_info->bmiHeader.biClrUsed = 0;	/* unused */
		bitmap_info->bmiHeader.biClrImportant = 0;
		((DWORD*)bitmap_info->bmiColors)[0] = 0x0000f800; // Rmask
		((DWORD*)bitmap_info->bmiColors)[1] = 0x000007e0; // Gmask
		((DWORD*)bitmap_info->bmiColors)[2] = 0x0000001f; // Bmask
	}
	else
	{
		bitmap_info->bmiHeader.biBitCount = 32;
		bitmap_info->bmiHeader.biCompression = BI_RGB;
		bitmap_info->bmiHeader.biClrUsed = 0;	/* unused */
		bitmap_info->bmiHeader.biClrImportant = 0;
		((DWORD*)bitmap_info->bmiColors)[0] = 0x00ff0000; // Rmask
		((DWORD*)bitmap_info->bmiColors)[1] = 0x0000ff00; // Gmask
		((DWORD*)bitmap_info->bmiColors)[2] = 0x000000ff; // Bmask
	}

	if (m_hBitmap != NULL)
		DeleteObject(m_hBitmap);
	hdc = GetDC(NULL);
	m_hBitmap = ::CreateDIBSection(hdc, bitmap_info, DIB_RGB_COLORS, &m_bmpPixels, NULL, 0);
	ReleaseDC(NULL, hdc);
	if (m_hBitmap == NULL)
		return false;
	
	m_screenBmp.reset();
	m_screenBmp.setConfig(m_bmpConfig, m_screenW, m_screenH);
	m_screenBmp.setHBITMAP(m_hBitmap);
	m_screenBmp.setPixels(m_bmpPixels);

	return true;
}

bool ReleaseBitmapWin(SkBitmapWin& bitmap_win)
{
	if (m_hBitmap != NULL)
		DeleteObject(m_hBitmap), m_hBitmap = NULL;
}

bool Draw()
{
	HDC hdc = GetDC(m_mainWnd);
	SkCanvasWin canvas(hdc, m_screenBmp);
	
	HDC dcMem = canvas.getDC();
	BitBlt(hdc, 0, 0, m_screenW, m_screenH, dcMem, 0, 0, SRCCOPY);
	ReleaseDC(m_mainWnd, hdc);
}

#endif